package cn.wolfcode.exception;

import cn.wolfcode.controller.JsonResult;
import com.alibaba.fastjson.JSON;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.method.HandlerMethod;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@ControllerAdvice
public class HandlerControllerException {


    @ExceptionHandler(RuntimeException.class)
    public Object handlerException(RuntimeException e, HttpServletResponse response, HandlerMethod method) {
        e.getStackTrace();
        if (method.hasMethodAnnotation(ResponseBody.class)) {
            String errorMsg = "操作失败,请联系管理员";
            if (e instanceof LogicException) {
                errorMsg = e.getMessage();
            }
            JsonResult json = new JsonResult(false, errorMsg);
            response.setContentType("application/json;charset=utf-8");
            try {
                response.getWriter().print(JSON.toJSONString(json));
            } catch (IOException e1) {
                e1.printStackTrace();
            }
            return null;
        } else {
            return "/common/error";
        }

    }

}
